// API配置
export const API_CONFIG = {
  // 基础URL - 请根据实际情况修改
  BASE_URL: "http://localhost:3000",

  // API端点
  ENDPOINTS: {
    // 认证相关
    LOGIN: "/auth/login",
    REGISTER: "/auth/register",
    SEND_VERIFICATION_CODE: "/auth/send-verification-code",
    LOGOUT: "/auth/logout",

    // 用户相关
    USER_INFO: "/auth/profile",
    UPDATE_PROFILE: "/auth/profile",

    // 消息相关
    MESSAGES: "/messages",
    SEND_MESSAGE: "/messages/send",
    CONVERSATIONS: "/chat/conversations",
    CREATE_CONVERSATION: "/chat/conversations",

    // 联系人相关
    CONTACTS: "/contacts",
    ADD_CONTACT: "/contacts/add",
    FRIENDS: "/friends",
    DELETE_FRIEND: "/friends",
    SEARCH_USERS: "/friends/search",
    SEND_FRIEND_REQUEST: "/friends/request",
    GET_FRIEND_REQUESTS: "/friends/requests",
    HANDLE_FRIEND_REQUEST: "/friends/requests",

    // 漂流瓶相关
    DRIFT_BOTTLES: "/drift-bottles",
    PICK_DRIFT_BOTTLE: "/drift-bottles/pick",

    // 其他
    UPLOAD: "/upload"
  },
};

// HTTP请求工具类
export class HttpClient {
  private static baseURL = API_CONFIG.BASE_URL;

  /**
   * 通用请求方法
   */
  static async request(options: {
    url: string;
    method?: "GET" | "POST" | "PUT" | "DELETE";
    data?: any;
    header?: Record<string, string>;
    needAuth?: boolean;
  }) {
    const { url, method = "GET", data, header = {}, needAuth = true } = options;

    // 构建完整URL
    const fullUrl = url.startsWith("http") ? url : `${this.baseURL}${url}`;

    // 设置默认请求头
    const defaultHeaders = {
      "Content-Type": "application/json",
    };

    // 如果需要认证，添加token
    if (needAuth) {
      const token = uni.getStorageSync("token");
      if (token) {
        defaultHeaders["Authorization"] = `Bearer ${token}`;
      }
    }

    try {
      const response = await uni.request({
        url: fullUrl,
        method,
        data,
        header: { ...defaultHeaders, ...header },
      });

      const result = response.data as any;

      // 统一处理响应
      if (result.code === 200) {
        return result;
      } else if (result.code === 401) {
        // token过期，清除本地存储并跳转到登录页
        uni.removeStorageSync("token");
        uni.removeStorageSync("userInfo");
        uni.reLaunch({
          url: "/pages/login",
        });
        throw new Error("登录已过期，请重新登录");
      } else {
        throw new Error(result.message || "请求失败");
      }
    } catch (error: any) {
      console.error("HTTP请求错误:", error);
      throw error;
    }
  }

  /**
   * GET请求
   */
  static get(url: string, params?: any, needAuth = true) {
    const queryString = params
      ? "?" +
        Object.keys(params)
          .map((key) => `${key}=${encodeURIComponent(params[key])}`)
          .join("&")
      : "";

    return this.request({
      url: url + queryString,
      method: "GET",
      needAuth,
    });
  }

  /**
   * POST请求
   */
  static post(url: string, data?: any, needAuth = true) {
    return this.request({
      url,
      method: "POST",
      data,
      needAuth,
    });
  }

  /**
   * PUT请求
   */
  static put(url: string, data?: any, needAuth = true) {
    return this.request({
      url,
      method: "PUT",
      data,
      needAuth,
    });
  }

  /**
   * DELETE请求
   */
  static delete(url: string, data?: any, needAuth = true) {
    return this.request({
      url,
      method: "DELETE",
      data,
      needAuth,
    });
  }
}

// 认证相关API
export const AuthAPI = {
  /**
   * 用户登录
   */
  login: (email: string, password: string) => {
    return HttpClient.post(
      API_CONFIG.ENDPOINTS.LOGIN,
      {
        email,
        password,
      },
      false
    ); // 登录不需要token
  },

  /**
   * 发送注册验证码
   */
  sendVerificationCode: (email: string) => {
    return HttpClient.post(
      API_CONFIG.ENDPOINTS.SEND_VERIFICATION_CODE,
      {
        email,
      },
      false
    ); // 发送验证码不需要token
  },

  /**
   * 用户注册
   */
  register: (userData: {
    email: string;
    password: string;
    nickName?: string;
    verificationCode: string;
    [key: string]: any;
  }) => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.REGISTER, userData, false);
  },

  /**
   * 用户登出
   */
  logout: () => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.LOGOUT);
  },
};

// 用户相关API
export const UserAPI = {
  /**
   * 获取用户信息
   */
  getUserInfo: () => {
    return HttpClient.get(API_CONFIG.ENDPOINTS.USER_INFO);
  },

  /**
   * 更新用户资料
   */
  updateProfile: (profileData: any) => {
    return HttpClient.put(API_CONFIG.ENDPOINTS.UPDATE_PROFILE, profileData);
  },
};

// 消息相关API
export const MessageAPI = {
  /**
   * 获取指定会话的消息列表
   * @param conversationId 会话ID
   * @param params 查询参数 { page?: number, limit?: number }
   */
  getMessages: (conversationId: string, params?: { page?: number; limit?: number }) => {
    const endpoint = `/chat/conversations/${conversationId}/messages`;
    return HttpClient.get(endpoint, params);
  },

  /**
   * 在指定会话中发送消息
   * @param conversationId 会话ID
   * @param content 消息内容
   */
  sendMessage: (conversationId: string, content: string) => {
    const endpoint = `/chat/conversations/${conversationId}/messages`;
    return HttpClient.post(endpoint, { content });
  },

  /**
   * 获取会话列表
   */
  getConversations: () => {
    return HttpClient.get(API_CONFIG.ENDPOINTS.CONVERSATIONS);
  },

  /**
   * 创建或获取会话
   */
  createConversation: (friendId: string) => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.CREATE_CONVERSATION, {
      friendId
    });
  },

  /**
   * 删除会话
   */
  deleteConversation: (conversationId: string | number) => {
    return HttpClient.delete(`/chat/conversations/${conversationId}`);
  },
};

// 联系人相关API
export const ContactAPI = {
  /**
   * 获取联系人列表
   */
  getContacts: () => {
    return HttpClient.get(API_CONFIG.ENDPOINTS.CONTACTS);
  },

  /**
   * 获取好友列表
   */
  getFriends: () => {
    return HttpClient.get(API_CONFIG.ENDPOINTS.FRIENDS);
  },

  /**
   * 搜索用户
   */
  searchUsers: (email: string) => {
    return HttpClient.get(API_CONFIG.ENDPOINTS.SEARCH_USERS, { email });
  },

  /**
   * 发送好友申请
   */
  sendFriendRequest: (email: string, message?: string) => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.SEND_FRIEND_REQUEST, {
      email,
      message: message || ''
    });
  },

  /**
   * 添加联系人
   */
  addContact: (contactData: any) => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.ADD_CONTACT, contactData);
  },

  /**
   * 获取收到的好友申请列表
   */
  getFriendRequests: () => {
    return HttpClient.get(API_CONFIG.ENDPOINTS.GET_FRIEND_REQUESTS);
  },

  /**
   * 处理好友申请
   */
  handleFriendRequest: (requestId: string, action: 1 | 2) => {
    return HttpClient.put(`${API_CONFIG.ENDPOINTS.HANDLE_FRIEND_REQUEST}/${requestId}`, {
      action
    });
  },

  /**
   * 删除好友
   */
  deleteFriend: (email: string) => {
    return HttpClient.delete(API_CONFIG.ENDPOINTS.DELETE_FRIEND, {
      email
    });
  },
};

// 动态相关API
export const PostAPI = {
  /**
   * 发布动态
   */
  createPost: (content: string) => {
    return HttpClient.post('/posts', { content });
  },

  /**
   * 获取好友动态
   */
  getFriendsPosts: (params?: { page?: number; limit?: number }) => {
    return HttpClient.get('/posts/friends', params);
  },

  /**
   * 删除动态
   */
  deletePost: (postId: string | number) => {
    return HttpClient.delete(`/posts/${postId}`);
  },

  /**
   * 点赞/取消点赞
   */
  toggleLike: (postId: string | number) => {
    return HttpClient.post(`/posts/${postId}/like`);
  },

  /**
   * 发表评论
   */
  createComment: (postId: string | number, content: string, parentId?: string | number) => {
    const data: any = { content };
    if (parentId) data.parentId = parentId;
    return HttpClient.post(`/posts/${postId}/comments`, data);
  },

  /**
   * 获取评论列表
   */
  getComments: (postId: string | number, params?: { page?: number; limit?: number }) => {
    return HttpClient.get(`/posts/${postId}/comments`, params);
  },
};

// 漂流瓶相关API
export const DriftBottleAPI = {
  /**
   * 扔出漂流瓶
   * @param content 漂流瓶内容
   */
  throwBottle: (content: string) => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.DRIFT_BOTTLES, { content });
  },

  /**
   * 捡起漂流瓶
   */
  pickBottle: () => {
    return HttpClient.post(API_CONFIG.ENDPOINTS.PICK_DRIFT_BOTTLE);
  },
};
